package cn.gavin.util;

import cn.gavin.domain.Employee;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpSession;
import java.util.List;

public class UserContext {
    // 抽取常量 session 中的数据
    public static final String PERMISSION_IN_SESSION = "PERMISSION_IN_SESSION";
    public static final String USER_IN_SESSION = "USER_IN_SESSION";

    // 使用 springmvc 提供工具类，获取 session 对象
    public static HttpSession getSession(){
        ServletRequestAttributes attributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        return attributes.getRequest().getSession();
    }

    public static void setUserInSession(Employee employee){
        getSession().setAttribute(USER_IN_SESSION,employee); // 把用户信息存到 session
    }

    public static void setPermissions(List<String> list){
        getSession().setAttribute(PERMISSION_IN_SESSION,list); // 把权限信息存到 session
    }

    public static Employee getCurrentUser(){
        return (Employee)getSession().getAttribute(USER_IN_SESSION); // 从 session 中取用户信息
    }

    public static List<String> getPermissions(){
        return (List<String>)getSession().getAttribute(PERMISSION_IN_SESSION);
    }
}
